package com.ali.niogroupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Set;

public class GroupChatServer {
    private final Selector selector;

    public GroupChatServer(int port) {
        try {
            //构建监听服务
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            //设置监听服务为非阻塞状态
            serverSocketChannel.configureBlocking(false);
            //绑定监听端口
            serverSocketChannel.bind(new InetSocketAddress(port));
            //构建多路复用器
            selector = Selector.open();
            //在多路复用器中注册客户端连接事件
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        GroupChatServer groupChatServer = new GroupChatServer(8080);
        groupChatServer.start();
    }

    /**
     * 启动
     */
    public void start() {
        try {
            while (true) {
                //多路复用器阻塞，等待事件发生
                selector.select();
                handle();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 处理多路复用器事件
     */
    private void handle() {
        try {
            //构建缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
            int length;

            //获取多路复用器的所有事件
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                //判断是否是客户端连接事件
                if (selectionKey.isAcceptable()) {
                    //获取监听服务
                    ServerSocketChannel serverSocketChannel = (ServerSocketChannel) selectionKey.channel();
                    //获取客户端连接
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    //设置客户端连接为非阻塞状态
                    socketChannel.configureBlocking(false);
                    //在多路复用器中注册数据传输事件
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    String message = socketChannel.getRemoteAddress() + "：上线";
                    System.out.println(message);
                    transmit(socketChannel, message);
                }
                //判断是否是数据传输事件
                else if (selectionKey.isReadable()) {
                    //获取客户端连接
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    StringBuilder stringBuffer = new StringBuilder();

                    try {
                        while (true) {
                            //写入内容至缓冲区
                            length = socketChannel.read(byteBuffer);
                            if (length > 0) {
                                //清理缓冲区
                                byteBuffer.clear();
                                stringBuffer.append(new String(byteBuffer.array(), 0, length));
                            } else if (length == 0) {
                                break;
                            } else if (length == -1) {
                                System.out.println(socketChannel.getRemoteAddress() + "：下线");
                                transmit(socketChannel, socketChannel.getRemoteAddress() + "：下线");
                                //取消注册
                                selectionKey.cancel();
                                break;
                            }
                        }
                        String message = socketChannel.getRemoteAddress() + "：" + stringBuffer;
                        System.out.println(message);
                        transmit(socketChannel, message);
                    } catch (IOException e) {
                        String message = socketChannel.getRemoteAddress() + "：下线";
                        System.out.println(message);
                        transmit(socketChannel, message);
                        //取消注册
                        selectionKey.cancel();
                    }
                }
                //移除事件
                iterator.remove();
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 向其他客户端转发
     */
    private void transmit(SocketChannel socketChannel, String content) throws IOException {
        //获取多路复用器的所有事件
        Set<SelectionKey> selectionKeys = selector.keys();
        for (SelectionKey selectionKey : selectionKeys) {
            //获取Channel
            Channel channel = selectionKey.channel();
            if (channel instanceof SocketChannel tempSocketChannel && socketChannel != tempSocketChannel) {
                //构建缓冲区
                ByteBuffer byteBuffer = ByteBuffer.wrap(content.getBytes(StandardCharsets.UTF_8));
                //向客户端连接传输数据
                tempSocketChannel.write(byteBuffer);
            }
        }
    }
}
